package net.zjitc.demo.controller;

import net.zjitc.demo.dao.BookDao;
import net.zjitc.demo.domain.Book;
import net.zjitc.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private BookDao bookDao;
    @GetMapping("/tests")
    public String test(Model model) {
        model.addAttribute("messages", bookService.getById(1));
        return "book";
    }
    @GetMapping("/books")
    public String book(Model model){
        List<Book> books=bookService.list();
        System.out.println("打印书籍信息"+books.size());
        books.forEach(System.out::println);
        model.addAttribute("books",books);
        return "book-list";
    }
    @GetMapping("/book-form")
    public String addBook(Model model) {
        model.addAttribute("book", new Book());
        return "book-form";
    }

    @PostMapping("/submit-book")
    public String submit(Model model, @ModelAttribute Book book) {
        bookDao.insert(book);
        model.addAttribute("book", book);
        return "book-result";
    }

    @GetMapping("/view-book")
    public String searchBook(Model model, @RequestParam Integer id) {
        Book book = bookDao.selectById(id);
        if (book == null) {
            return "error";
        }
        model.addAttribute("book", book);
        return "book-detail";
    }

    @GetMapping("/book/edit/{id}")
    public String editBook(Model model, @PathVariable Integer id) {
        Book book = bookDao.selectById(id);
        if (book == null) {
            return "error";
        }
        model.addAttribute("book", book);
        return "book-edit";
    }

    @PostMapping("/book/update")
    public String updateBook(Model model, @ModelAttribute Book book) {
        bookDao.updateById(book);
        model.addAttribute("book", book);
        return "book-detail";
    }
    @PostMapping("/delete-book")
    public String deleteBook(@RequestParam("id") Integer id){
      boolean deleted = bookService.removeById(id);
      if (deleted){
          return "success";
      }else{
          return "error";
      }
    }
}